package asionreachel.cn.smarthomedemo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;

import asionreachel.cn.smarthomedemo.R;
import asionreachel.cn.smarthomedemo.adapter.DividerGridItemDecoration;
import asionreachel.cn.smarthomedemo.adapter.GridAdapter;
import asionreachel.cn.smarthomedemo.base.BaseActivity;
import asionreachel.cn.smarthomedemo.base.BaseDevice;
import asionreachel.cn.smarthomedemo.base.Common;
import asionreachel.cn.smarthomedemo.base.ConstantDefinition;
import asionreachel.cn.smarthomedemo.data.CDeviceTypeInfo;
import asionreachel.cn.smarthomedemo.device.SlidingMenuMgr;
import asionreachel.cn.smarthomedemo.listener.OnRecyleItemListener;
import asionreachel.cn.smarthomedemo.widget.filter.FilterImageView;
import familyclient.android.common.JToolFunc;
import familyclient.android.device.cdm1.JDevice_CDM1Interface;
import familyclient.android.device.cdm1.JDevice_CDM1Listener;

public class SelectDeviceActivity extends BaseActivity {
    private static final String TAG = "SelectActivity";
    private static final String FUNCTION = "DeviceList";

    private RecyclerView m_rvDeviceList;
    private FilterImageView m_fivRefresh;
    private ArrayList<CDeviceTypeInfo> m_listDevice = new ArrayList();        //列表显示内容
    private GridAdapter m_adapterDevice;


    private JDevice_CDM1Listener m_listenerCDM1 = new JDevice_CDM1Listener()
    {
        @Override
        public void CbDeviceInfoUpdatedCb(String a_strDeviceID) {
            Log.i("JDevice_CDM1Listener", "CbDeviceInfoUpdatedCb");
            if( !m_bRun )
                return;

            int iIndex = getIndexByTag( ConstantDefinition.CDM1 );
            if( iIndex >= 0 )
            {
                if( m_listDevice.get( iIndex ).IsDeviceIDExist( a_strDeviceID ) )
                {
                    JDevice_CDM1Interface.GetInstance().GetDeviceInfo(a_strDeviceID);
                    return;
                }
            }
            JDevice_CDM1Interface.GetInstance().GetDeviceInfoList();
        }

        @Override
        public void CbDeviceInfoListUpdatedCb() {
            Log.i("JDevice_CDM1Listener", "CbDeviceInfoListUpdatedCb");
            if( !m_bRun )
                return;

            JDevice_CDM1Interface.GetInstance().GetDeviceInfoList();
        }

        @Override
        public void GetDeviceInfoCb(familyclient.java.device.cdm1.data.JDeviceInfoData a_dataDeviceInfo, String a_strErr) {
            Log.i("JDevice_CDM1Listener", "GetDeviceInfoCb");
            if( !m_bRun )
                return;
            if ( ( a_strErr != null && !a_strErr.isEmpty() ) || null == a_dataDeviceInfo )
            {
                //获取失败
                Common.showToast( Common.MakeMsgByErr( FUNCTION, a_strErr ) );
            }
            else
            {
                int iIndex = getIndexByTag( ConstantDefinition.CDM1 );
                if( iIndex < 0 )
                {
                    JDevice_CDM1Interface.GetInstance().GetDeviceInfoList();
                }
                else
                {
                    m_listDevice.get( iIndex ).addDevice( a_dataDeviceInfo.m_strDeviceID , a_dataDeviceInfo.m_bOnline , a_dataDeviceInfo.m_strDeviceName);
                    m_adapterDevice.addData( iIndex , m_listDevice.get( iIndex ) );
                }
            }
        }

        @Override
        public void GetDeviceInfoListCb(familyclient.java.device.cdm1.data.JDeviceInfoListData a_listDeviceInfo, String a_strErr) {
            Log.i("JDevice_CDM1Listener", "GetDeviceInfoListCb");
            if( !m_bRun )
                return;
            if (a_strErr != null && !a_strErr.isEmpty())
            {
                Common.showToast( Common.MakeMsgByErr( FUNCTION, a_strErr ) );
            }
            else
            {
                int iIndex = getIndexByTag( ConstantDefinition.CDM1 );
                if( a_listDeviceInfo.GetSize() > 0 && iIndex < 0 )
                {
                    ConstantDefinition.CDeviceInfo device = ConstantDefinition.CDeviceInfo.getDeviceInfo( ConstantDefinition.CDM1 );
                    if( null == device )
                        return;

                    CDeviceTypeInfo info = new CDeviceTypeInfo();
                    info.setDeviceInfo( device.getName(), device.getIcon(), device.getTag() );
                    m_listDevice.add( info );
                    iIndex = m_listDevice.size() - 1;
                }
                else if( 0 == a_listDeviceInfo.GetSize() && iIndex >= 0 )
                {
                    // m_listDevice.remove( iIndex );   // m_adapterDevice & m_listDevice is same data, don't double remove
                    m_adapterDevice.removeData( iIndex );
                    iIndex = -1;
                }

                if( iIndex >= 0 )
                {
                    m_listDevice.get( iIndex ).clearDevice();
                    for( int i = 0; i < a_listDeviceInfo.GetSize(); i++ )
                    {
                        familyclient.java.device.cdm1.data.JDeviceInfoData deviceData = a_listDeviceInfo.GetData(i);
                        m_listDevice.get( iIndex ).addDevice(deviceData.m_strDeviceID , deviceData.m_bOnline , deviceData.m_strDeviceName);
                    }
                    if( a_listDeviceInfo.GetSize() > 0 )
                        m_adapterDevice.addData( iIndex, m_listDevice.get( iIndex ) );
                }
            }
        }
    };


    public void initWidget() {
        initDeviceData();
        JDevice_CDM1Interface.GetInstance().AddListener(m_listenerCDM1);
        m_adapterDevice = new GridAdapter(getApplicationContext());
        m_adapterDevice.setAdapterData(m_listDevice);
        m_rvDeviceList = (RecyclerView)findViewById(R.id.device_rv_list);
        m_rvDeviceList.setLayoutManager(new GridLayoutManager(this , 4));
        m_rvDeviceList.setAdapter(m_adapterDevice);
        m_rvDeviceList.addItemDecoration(new DividerGridItemDecoration(getApplicationContext()));
        m_fivRefresh = (FilterImageView)findViewById(R.id.select_flv_refresh);
    }

    public void initListener() {
        m_fivRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        m_adapterDevice.setOnRecyleItemListener(new OnRecyleItemListener() {
            @Override
            public void onItemClick(int position) {
                //请求对应的设备信息,进入主界面
                if (m_listDevice.get(position).getCount() == 0)
                {
                    //Common.showToast("此设备数为0");
                    return;
                }

                String strDeviceID = Common.getDeviceIDWithTag( m_listDevice.get(position).getTag() );
                if( null == strDeviceID || 0 == strDeviceID.length() || !m_listDevice.get(position).IsDeviceIDExist( strDeviceID ) )
                    strDeviceID = m_listDevice.get(position).getDeviceInfoDataByIndex(0).getDeviceId();
                Intent intent = BaseDevice.GetIntent( mActivity, strDeviceID );
                String deviceType = JToolFunc.DeviceIDToDeviceType( strDeviceID );
                SlidingMenuMgr.getInstance().setSelectPosition(0);      //默认下标为0
                SlidingMenuMgr.getInstance().setDeviceTag( deviceType );
                if( intent != null )
                    startActivity(intent);
                else
                    Common.showToast("当前功能尚未完成");
            }
        });

        ImageView btPersonalCenter = (ImageView)findViewById(R.id.iv_personal_center);
        btPersonalCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Common.openPersonalCenter(mActivity);
            }
        });
        ImageView btDeviceAdd = (ImageView)findViewById(R.id.iv_add);
        btDeviceAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Common.openAddDevice(mActivity);
            }
        });
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mActivity = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_device);
        initWidget();
        initListener();
    }

    //刷新设备
    private void onRefresh()
    {
        BaseDevice.GetAllDeviceInfoList();
    }

    //更新索引
    private void initDeviceData()
    {
        //int i = 0;      //初始化索引
        m_listDevice = new ArrayList();
        for (ConstantDefinition.CDeviceInfo device : ConstantDefinition.CDeviceInfo.values())
            device.setIndex(-1);
    }

    //通过数据请求，有设备时才添加进去
    private int getIndexByTag( String a_strTag )
    {
        int iIndex = 0;
        for( iIndex = 0 ; iIndex < m_listDevice.size() ; ++iIndex )
        {
            if( m_listDevice.get( iIndex ).getTag().equals( a_strTag ) )
                break;
        }
        if( iIndex >= m_listDevice.size() )
            iIndex = -1;

        return iIndex;
    }

    @Override
    protected void onDestroy()
    {
        JDevice_CDM1Interface.GetInstance().DelListener(m_listenerCDM1);
        super.onDestroy();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        onRefresh();
    }
}
